package jee.boot.module.oauth2.service;

import jee.boot.common.basic.CrudService;
import jee.boot.common.basic.Page;
import jee.boot.entity.auth.Account;
import jee.boot.entity.system.Filter;
import jee.boot.entity.system.SystemConfig;
import jee.boot.module.oauth2.dao.AccountHistoryPasswordDao;
import jee.boot.entity.auth.AccountHistoryPassword;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 账户历史密码
 */
@Service
public class AccountHistoryPasswordService extends CrudService<AccountHistoryPasswordDao, AccountHistoryPassword> {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private Integer DEFAULT_HISTORY_PASSWORD_SAVE_TIMES = 3;//默认历史密码保存次数

    /**
     * 保存新的历史密码
     *
     * @param entity
     */
    @Override
    public void save(AccountHistoryPassword entity) {
        SystemConfig query1 = new SystemConfig();
        query1.setCode("HISTORY_PASSWORD_SAVE_TIMES");
        SystemConfig config = remoteEndpoint.executePost(projectConfig.getOpenSystemServer(), "/config/getByCode", query1, SystemConfig.class);
        Integer timesInt = config.getCode() == null ? DEFAULT_HISTORY_PASSWORD_SAVE_TIMES : Integer.parseInt(config.getValue());

        // 当设置的保留次数大于0的时候,才会启用改功能
        if (timesInt > 0) {
            super.save(entity);
            AccountHistoryPassword query = new AccountHistoryPassword();
            query.addFilter(new Filter("account.id", "=", entity.getAccount().getId()));
            List<AccountHistoryPassword> list = findList(query);
            // 删除历史中最旧的密码,保留指定次数内的数据
            if (list != null && list.size() > timesInt) {
                for (int i = 0; i < list.size(); i++) {
                    if (i > timesInt) {
                        delete(list.get(i));
                    }
                }
            }

        }

    }

    @Override
    public List<AccountHistoryPassword> findList(AccountHistoryPassword entity) {
        Page<AccountHistoryPassword> page = entity.getPage();
        if (page == null) {
            page = new Page<>();
            entity.setPage(page);
        }
        page.setOrderBy("createDate");
        page.setOrderSort("desc");// 查询按从大到小的顺序排序,方便后面对最旧的数据进行删除
        return super.findList(entity);
    }

    /**
     * 验证当前账户的密码是否与历史中的密码重复
     *
     * @param account
     * @return
     */
    public boolean checkPasswordRepeated(Account account) {
        SystemConfig query1 = new SystemConfig();
        query1.setCode("HISTORY_PASSWORD_SAVE_TIMES");
        SystemConfig config = remoteEndpoint.executePost(projectConfig.getOpenSystemServer(), "/config/getByCode", query1, SystemConfig.class);
        Integer timesInt = config.getCode() == null ? DEFAULT_HISTORY_PASSWORD_SAVE_TIMES : Integer.parseInt(config.getValue());
        // 当设置的保留次数大于0的时候,才会启用改功能,删除历史中最旧的密码,保留指定次数内的数据
        if (timesInt > 0) {
            AccountHistoryPassword query = new AccountHistoryPassword();
            query.addFilter(new Filter("account.id", "=", account.getId()));
            List<AccountHistoryPassword> list = findList(query);
            for (AccountHistoryPassword old : list) {
                if (validatePassword(account.getNewPassword(), old.getPassword())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 验证密码
     *
     * @param plainPassword 明文密码
     * @param password      密文密码
     * @return 验证成功返回true
     */
    public static boolean validatePassword(String plainPassword, String password) {
        return new BCryptPasswordEncoder().matches(plainPassword, password);
    }

}
